package com.cvs.controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.cvs.model.UserEntity;
import com.cvs.services.ChmService;

@Controller
public class LogInController {

	@Autowired
	private ChmService controllerService;

	public ChmService getControllerService() {
		return controllerService;
	}

	public void setControllerService(ChmService controllerService) {
		this.controllerService = controllerService;
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView getLoginPage() {

		String message = "hello";
		return new ModelAndView("login", "messsage", message);
	}
	
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public ModelAndView getRegisterPage() {

		String message = "hello";
		return new ModelAndView("register", "messsage", message);
	}

	@RequestMapping(value = "/denied", method = RequestMethod.GET)
	public ModelAndView getRegPage() {

		String message = "hello";
		return new ModelAndView("denied", "messsage", message);
	}

	@RequestMapping(value = "/createUser", method = RequestMethod.POST)
	public String createNewUser(HttpServletRequest req, ModelMap model,
			HttpSession session, HttpServletResponse resp) throws IOException {

		UserEntity user = new UserEntity();
		user.setUserName(req.getParameter("j_username"));
		user.setFirstName(req.getParameter("j_name"));
		user.setEmailAddress(req.getParameter("j_email"));
		user.setLastName(req.getParameter("l_name"));
		System.out.println(req.getParameter("j_name")
				+ req.getParameter("j_username"));
		user.setDate(new Date());
		user.setAccessLevel(2);
		user.setAllocation(20);
		user.setOriginalAllocation(20);
		Md5PasswordEncoder encode = new Md5PasswordEncoder();
		String pw = encode.encodePassword(req.getParameter("j_password"), null);
		user.setPassword(pw);

		// String username = req.getParameter("j_username");
		// String fullName = req.getParameter("j_name");
		// String password = req.getParameter("j_password");
		// controllerService.createUserRecord(username, password, fullName);
		controllerService.storeUser(user);
		return "book";
	}
}
